import React, {useEffect, useRef, useState} from 'react';
import ReactMarkdown from 'react-markdown';
import {Typography} from 'antd';
import rehypeRaw from 'rehype-raw';
// 新增：引入 remark-gfm 插件用于支持表格渲染
import remarkGfm from 'remark-gfm';

// 新增：引入 highlight.js 语法高亮库及样式文件
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css'; // 可根据喜好选择不同主题样式

const {Paragraph} = Typography;
import './index.css';
import {
    AppstoreAddOutlined,
    CloudUploadOutlined,
    CommentOutlined,
    CopyOutlined,
    DeleteOutlined,
    DislikeOutlined,
    EditOutlined,
    EllipsisOutlined,
    FileSearchOutlined,
    HeartOutlined,
    LikeOutlined,
    PaperClipOutlined,
    PlusOutlined,
    ProductOutlined,
    QuestionCircleOutlined,
    ReloadOutlined,
    ScheduleOutlined,
    ShareAltOutlined,
    SmileOutlined,
} from '@ant-design/icons';
import {
    Attachments,
    Bubble,
    Conversations,
    Prompts,
    Sender,
    Welcome,
    useXAgent,
    useXChat,
} from '@ant-design/x';
import {Avatar, Button, Flex, type GetProp, Space, Spin, message} from 'antd';
import {createStyles} from 'antd-style';
import dayjs from 'dayjs';
import {Modal} from 'antd'; // 引入 Modal 组件

type BubbleDataType = {
    role: string;
    content: string;
};

const DEFAULT_CONVERSATIONS_ITEMS = [
    {
        key: 'default-0',
        label: 'What is Ant Design X?',
        group: 'Today',
    },
    {
        key: 'default-1',
        label: 'How to quickly install and import components?',
        group: 'Today',
    },
    {
        key: 'default-2',
        label: 'New AGI Hybrid Interface',
        group: 'Yesterday',
    },
];

const HOT_TOPICS = {
    key: '1',
    label: 'Hot Topics',
    children: [
        {
            key: '1-1',
            description: 'What has Ant Design X upgraded?',
            icon: <span style={{color: '#f93a4a', fontWeight: 700}}>1</span>,
        },
        {
            key: '1-2',
            description: 'New AGI Hybrid Interface',
            icon: <span style={{color: '#ff6565', fontWeight: 700}}>2</span>,
        },
        {
            key: '1-3',
            description: 'What components are in Ant Design X?',
            icon: <span style={{color: '#ff8f1f', fontWeight: 700}}>3</span>,
        },
        {
            key: '1-4',
            description: 'Come and discover the new design paradigm of the AI era.',
            icon: <span style={{color: '#00000040', fontWeight: 700}}>4</span>,
        },
        {
            key: '1-5',
            description: 'How to quickly install and import components?',
            icon: <span style={{color: '#00000040', fontWeight: 700}}>5</span>,
        },
    ],
};

const DESIGN_GUIDE = {
    key: '2',
    label: 'Design Guide',
    children: [
        {
            key: '2-1',
            icon: <HeartOutlined/>,
            label: 'Intention',
            description: 'AI understands user needs and provides solutions.',
        },
        {
            key: '2-2',
            icon: <SmileOutlined/>,
            label: 'Role',
            description: "AI's public persona and image",
        },
        {
            key: '2-3',
            icon: <CommentOutlined/>,
            label: 'Chat',
            description: 'How AI Can Express Itself in a Way Users Understand',
        },
        {
            key: '2-4',
            icon: <PaperClipOutlined/>,
            label: 'Interface',
            description: 'AI balances "chat" & "do" behaviors.',
        },
    ],
};

const SENDER_PROMPTS: GetProp<typeof Prompts, 'items'> = [
    {
        key: '1',
        description: '你好',
        icon: <ScheduleOutlined/>,
    }
];

const useStyle = createStyles(({token, css}) => {
    return {
        layout: css`
            width: 100%;
            min-width: 1000px;
            height: calc(100vh - 16px);
            display: flex;
            background: ${token.colorBgContainer};
            font-family: AlibabaPuHuiTi, ${token.fontFamily}, sans-serif;
        `,
        // sider 样式
        sider: css`
            background: ${token.colorBgLayout}80;
            width: 280px;
            height: 100%;
            display: flex;
            flex-direction: column;
            padding: 0 12px;
            box-sizing: border-box;
        `,
        logo: css`
            display: flex;
            align-items: center;
            justify-content: start;
            padding: 0 24px;
            box-sizing: border-box;
            gap: 8px;
            margin: 24px 0;

            span {
                font-weight: bold;
                color: ${token.colorText};
                font-size: 16px;
            }
        `,
        addBtn: css`
            background: #1677ff0f;
            border: 1px solid #1677ff34;
            height: 40px;
        `,
        conversations: css`
            flex: 1;
            overflow-y: auto;
            margin-top: 12px;
            padding: 0;

            .ant-conversations-list {
                padding-inline-start: 0;
            }
        `,
        siderFooter: css`
            border-top: 1px solid ${token.colorBorderSecondary};
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        `,
        // chat list 样式
        chat: css`
            height: 100%;
            width: 100%;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            padding-block: ${token.paddingLG}px;
            gap: 16px;
        `,
        chatPrompt: css`
            .ant-prompts-label {
                color: #000000e0 !important;
            }

            .ant-prompts-desc {
                color: #000000a6 !important;
                width: 100%;
            }

            .ant-prompts-icon {
                color: #000000a6 !important;
            }
        `,
        chatList: css`
            flex: 1;
            overflow: auto;
        `,
        loadingMessage: css`
            background-image: linear-gradient(90deg, #ff6b23 0%, #af3cb8 31%, #53b6ff 89%);
            background-size: 100% 2px;
            background-repeat: no-repeat;
            background-position: bottom;
        `,
        message: css`
            .ant-message {
                z-index: 1001 !important;
            }
        `,
        placeholder: css`
            padding-top: 32px;
        `,
        // sender 样式
        sender: css`
            width: 100%;
            max-width: 700px;
            margin: 0 auto;
        `,
        speechButton: css`
            font-size: 18px;
            color: ${token.colorText} !important;
        `,
        senderPrompt: css`
            width: 100%;
            max-width: 700px;
            margin: 0 auto;
            color: ${token.colorText};
        `,
    };
});

const Independent: React.FC = () => {
    const {styles} = useStyle();
    const abortController = useRef<AbortController>(null);

    // 新增：消息历史状态管理
    const [messageHistory, setMessageHistory] = useState<Record<string, any>>({});

    // 新增：用于控制预览按钮的禁用状态
    const [isPreviewDisabled, setIsPreviewDisabled] = useState(false);

    // 新增侧边栏状态 (添加以下两行)
    const [isSidebarVisible, setIsSidebarVisible] = useState(false);
    const [sidebarContent, setSidebarContent] = useState('');

    // 新增预览模式状态
    const [isPreviewMode, setIsPreviewMode] = useState(false);

    // 修改显示模态框的函数
    const showModal = (htmlContent: string) => {
        if (isHtmlComplete(htmlContent)) {
            setSidebarContent(htmlContent);
            setIsSidebarVisible(true);
            setIsPreviewMode(true); // 进入预览模式
        } else {
            alert('HTML代码不完整，无法预览！');
            setIsPreviewDisabled(true);
        }
    };

    // 检查HTML内容是否完整的函数
    const isHtmlComplete = (htmlContent: string) => {
        // 创建一个div元素来装载HTML内容
        const div = document.createElement('div');
        div.innerHTML = htmlContent;

        // 获取所有打开的标签
        const openTags = [];
        const tagRegex = /<([a-zA-Z][a-zA-Z0-9]*)/g;
        let match;

        while ((match = tagRegex.exec(htmlContent)) !== null) {
            const tagName = match[1].toLowerCase();
            if (!/^(br|hr|img|input|link|meta|area|base|col|command|embed|keygen|param|source|track|wbr)$/i.test(tagName)) {
                if (!new RegExp(`<\\/${tagName}>`, 'i').test(htmlContent)) {
                    openTags.push(tagName);
                }
            }
        }

        // 如果有未闭合的标签，则返回false
        return openTags.length === 0;
    };

    const [conversations, setConversations] = useState(DEFAULT_CONVERSATIONS_ITEMS);
    const [curConversation, setCurConversation] = useState(DEFAULT_CONVERSATIONS_ITEMS[0].key);

    const [attachmentsOpen, setAttachmentsOpen] = useState(false);
    const [attachedFiles, setAttachedFiles] = useState<GetProp<typeof Attachments, 'items'>>([]);

    const [inputValue, setInputValue] = useState('');

    /**
     * 🔔 Please replace the BASE_URL, PATH, MODEL, API_KEY with your own values.
     */

        // ==================== Runtime ====================
    const id = new URLSearchParams(window.location.search).get("id");
    const [agent] = useXAgent<BubbleDataType>({
        baseURL: `/ai/agent/chat/${id}`
    });
    const loading = agent.isRequesting();

    const [isStreaming, setIsStreaming] = useState(false);

    const {onRequest, messages, setMessages} = useXChat({
        agent,
        requestFallback: (_, {error}) => {
            if (error.name === 'AbortError') {
                return {
                    content: 'Request is aborted',
                    role: 'assistant',
                };
            }
            return {
                content: 'Request failed, please try again!',
                role: 'assistant',
            };
        },
        transformMessage: (info) => {
            const {originMessage, chunk} = info || {};
            let currentContent = '';
            try {
                if (chunk?.data && !chunk?.data.includes('DONE')) {
                    const message = JSON.parse(chunk?.data);
                    if (message.content) {
                        currentContent = message.content;
                    } else if (message.toolCalls) {
                        currentContent = currentContent + "<details><summary>工具调用 " + message.toolCalls[0].name + "</summary><div style=\"border-left: 3px solid #ccc; padding-left: 10px;\">";
                        currentContent = currentContent + JSON.stringify(message.toolCalls[0].arguments);
                        currentContent = currentContent + "</div></details>";
                    } else if (message.toolCallsRaw) { // 工具消息
                        if (message.toolCallsRaw[0].function.name) {
                            currentContent = currentContent + "<details><summary>工具调用 " + message.toolCallsRaw[0].function.name + "</summary><div style=\"border-left: 3px solid #ccc; padding-left: 10px;\">";
                        }
                        currentContent = currentContent + message.toolCallsRaw[0].function.arguments;
                    } else {
                        // 补全
                        if (originMessage.content.includes("<details><summary>")) {
                            currentContent = currentContent + "</div></details>";
                        }
                    }
                }
            } catch (error) {
                console.error(error);
            }

            if (currentContent.includes("<think>")) {
                currentContent = currentContent.replace("<think>", "<details open><summary>深度思考</summary><div style=\"border-left: 3px solid #ccc; padding-left: 10px;\">");
            } else if (currentContent.includes("</think>")) {
                currentContent = currentContent.replace("</think>", "</div></details>");
                currentContent = currentContent + "\n";
            }

            let content = '';

            content = `${originMessage?.content || ''}${currentContent}`;

            // 检查HTML内容是否完整并更新预览按钮状态
            if (content.includes("<html>") && content.includes("</html>") && isHtmlComplete(content)) {
                setIsPreviewDisabled(false);
                // 新增：当检测到完整HTML内容时自动触发预览
                // 截取最新的html片段作为html内容
                showModal(content.match(/<html.*?>([\s\S]*?)<\/html>/)?.[1] || '');
            } else {
                setIsPreviewDisabled(true);
            }

            return {
                content: content,
                role: 'assistant',
            };
        },
        resolveAbortController: (controller) => {
            abortController.current = controller;
        },
    });

    // ==================== Event ====================
    const onSubmit = (val: string) => {
        if (!val) return;

        if (loading) {
            message.error('Request is in progress, please wait for the request to complete.');
            return;
        }

        onRequest({
            stream: true,
            message: {role: 'user', content: val},
        });
    };

    // ==================== Nodes ====================
    const chatSider = (
        <div className={styles.sider}>
            {/* 🌟 Logo */}
            <div className={styles.logo}>
                <img
                    src="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*eco6RrQhxbMAAAAAAAAAAAAADgCCAQ/original"
                    draggable={false}
                    alt="logo"
                    width={24}
                    height={24}
                />
                <span>大模型chat</span>
            </div>

            {/* 🌟 添加会话 */}
            <Button
                onClick={() => {
                    const now = dayjs().valueOf().toString();
                    setConversations([
                        {
                            key: now,
                            label: `New Conversation ${conversations.length + 1}`,
                            group: 'Today',
                        },
                        ...conversations,
                    ]);
                    setCurConversation(now);
                    setMessages([]);
                }}
                type="link"
                className={styles.addBtn}
                icon={<PlusOutlined/>}
            >
                New Conversation
            </Button>

            {/* 🌟 会话管理 */}
            <Conversations
                items={conversations}
                className={styles.conversations}
                activeKey={curConversation}
                onActiveChange={async (val) => {
                    abortController.current?.abort();
                    // The abort execution will trigger an asynchronous requestFallback, which may lead to timing issues.
                    // In future versions, the sessionId capability will be added to resolve this problem.
                    setTimeout(() => {
                        ``
                        setCurConversation(val);
                        setMessages(messageHistory?.[val] || []);
                    }, 100);
                }}
                groupable
                styles={{item: {padding: '0 8px'}}}
                menu={(conversation) => ({
                    items: [
                        {
                            label: 'Rename',
                            key: 'rename',
                            icon: <EditOutlined/>,
                        },
                        {
                            label: 'Delete',
                            key: 'delete',
                            icon: <DeleteOutlined/>,
                            danger: true,
                            onClick: () => {
                                const newList = conversations.filter((item) => item.key !== conversation.key);
                                const newKey = newList?.[0]?.key;
                                setConversations(newList);
                                // The delete operation modifies curConversation and triggers onActiveChange, so it needs to be executed with a delay to ensure it overrides correctly at the end.
                                // This feature will be fixed in a future version.
                                setTimeout(() => {
                                    if (conversation.key === curConversation) {
                                        setCurConversation(newKey);
                                        setMessages(messageHistory?.[newKey] || []);
                                    }
                                }, 200);
                            },
                        },
                    ],
                })}
            />

            <div className={styles.siderFooter}>
                <Avatar size={24}/>
                <Button type="text" icon={<QuestionCircleOutlined/>}/>
            </div>
        </div>
    );
    const chatList = (
        <div className={styles.chatList}>
            {messages?.length ? (
                /* 🌟 消息列表 */
                <Bubble.List
                    items={messages?.map((i) => ({
                        ...i.message,
                        content: (
                            <Paragraph style={{
                                maxWidth: '100%',
                                overflow: 'hidden',
                                // 新增消息背景色样式
                                // 白色背景
                                backgroundColor: 'white', // 浅灰色背景
                                padding: 12, // 增加内边距
                                borderRadius: 8, // 圆角边框
                                margin: '8px 0' // 调整外边距
                            }}>
                                <ReactMarkdown
                                    rehypePlugins={[rehypeRaw]}
                                    remarkPlugins={[remarkGfm]} // 新增 remark-gfm 插件支持表格
                                    components={{
                                        img: ({node, ...props}) => (
                                            <img
                                                {...props}
                                                style={{
                                                    maxWidth: '100%',
                                                    height: 'auto',
                                                    display: 'block',
                                                    margin: '8px 0'
                                                }}
                                            />
                                        ),
                                        // 新增：添加表格样式处理
                                        table: ({children}) => (
                                            <table style={{
                                                borderCollapse: 'collapse',
                                                width: '100%',
                                                margin: '16px 0',
                                                border: '1px solid #ddd'
                                            }}>{children}</table>
                                        ),
                                        th: ({children}) => (
                                            <th style={{
                                                border: '1px solid #ddd',
                                                padding: '8px',
                                                backgroundColor: '#f5f5f5',
                                                fontWeight: 'bold'
                                            }}>{children}</th>
                                        ),
                                        td: ({children}) => (
                                            <td style={{
                                                border: '1px solid #ddd',
                                                padding: '8px'
                                            }}>{children}</td>
                                        ),
                                        pre: ({children}) => (
                                            <pre style={{maxWidth: '100%', overflowX: 'auto'}}>{children}</pre>
                                        ),
                                        code: ({className, children}) => {
                                            if (children) {
                                                const match = /language-(\w+)/.exec(className || '');
                                                const lang = match && match[1] ? match[1] : '';
                                                const codeText = React.Children.toArray(children).join(''); // 改用更可靠的文本获取方式
                                                const highlightedCode = lang ? hljs.highlight(codeText, {language: lang}).value : codeText;

                                                // 新增复制功能处理逻辑
                                                const handleCopy = async () => {
                                                    try {
                                                        if (!codeText) {
                                                            message.warning('没有可复制内容');
                                                            return;
                                                        }
                                                        await navigator.clipboard.writeText(codeText);
                                                        message.success('复制成功');
                                                    } catch (err) {
                                                        console.error('复制失败:', err);
                                                        message.error('复制失败，请手动复制');
                                                    }
                                                };

                                                // 统一处理所有代码语言的复制按钮
                                                return (
                                                    <div style={{position: 'relative'}}>
                                                        <div style={{
                                                            position: 'absolute',
                                                            top: 0,
                                                            right: 0,
                                                            zIndex: 1,
                                                            display: 'flex',
                                                            gap: 4
                                                        }}>
                                                            {/* 仅在多行代码时显示复制按钮 */}
                                                            {codeText.includes('\n') && (
                                                                <Button
                                                                    size="small"
                                                                    type="text"
                                                                    icon={<CopyOutlined/>}
                                                                    onClick={handleCopy}
                                                                    style={{
                                                                        color: '#fff',
                                                                        background: '#00000050',
                                                                        borderRadius: 4
                                                                    }}
                                                                />
                                                            )}
                                                            {/* 保留原有的HTML预览按钮 */}
                                                            {lang === 'html' && (
                                                                <Button
                                                                    size="small"
                                                                    type="text"
                                                                    onClick={() => showModal(children.toString())}
                                                                    disabled={!isHtmlComplete(children.toString())}
                                                                    style={{
                                                                        color: '#fff',
                                                                        background: !isHtmlComplete(children.toString()) ? '#ccc' : '#1890ff',
                                                                        borderRadius: 4
                                                                    }}
                                                                >
                                                                    预览
                                                                </Button>
                                                            )}
                                                        </div>
                                                        <code className={className}
                                                              dangerouslySetInnerHTML={{__html: highlightedCode}}/>
                                                    </div>
                                                );
                                            }
                                        }
                                    }}>{i.message.content}</ReactMarkdown>
                            </Paragraph>
                        ),
                        classNames: {
                            content: i.status === 'loading' ? styles.loadingMessage : '',
                        },
                        typing: i.status === 'loading' ? {step: 5, interval: 20, suffix: <>💗</>} : false,
                    }))}
                    style={{height: '100%', paddingInline: 'calc(calc(100% - 700px) /2)'}}
                    roles={{
                        assistant: {
                            placement: 'start',
                            footer: (
                                <div style={{display: 'flex'}}>
                                    <Button type="text" size="small" icon={<ReloadOutlined/>}/>
                                    <Button type="text" size="small" icon={<CopyOutlined/>}/>
                                    <Button type="text" size="small" icon={<LikeOutlined/>}/>
                                    <Button type="text" size="small" icon={<DislikeOutlined/>}/>
                                </div>
                            ),
                            loadingRender: () => <Spin size="small"/>,
                        },
                        user: {placement: 'end'},
                    }}
                />
            ) : (
                <Space
                    direction="vertical"
                    size={16}
                    style={{paddingInline: 'calc(calc(100% - 700px) /2)'}}
                    className={styles.placeholder}
                >
                    <Welcome
                        variant="borderless"
                        icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
                        title="Hello, I'm Ant Design X"
                        description="Base on Ant Design, AGI product interface solution, create a better intelligent vision~"
                        extra={
                            <Space>
                                <Button icon={<ShareAltOutlined/>}/>
                                <Button icon={<EllipsisOutlined/>}/>
                            </Space>
                        }
                    />
                    {/*<Flex gap={16}>
            <Prompts
              items={[HOT_TOPICS]}
              styles={{
                list: { height: '100%' },
                item: {
                  flex: 1,
                  backgroundImage: 'linear-gradient(123deg, #e5f4ff 0%, #efe7ff 100%)',
                  borderRadius: 12,
                  border: 'none',
                },
                subItem: { padding: 0, background: 'transparent' },
              }}
              onItemClick={(info) => {
                onSubmit(info.data.description as string);
              }}
              className={styles.chatPrompt}
            />

            <Prompts
              items={[DESIGN_GUIDE]}
              styles={{
                item: {
                  flex: 1,
                  backgroundImage: 'linear-gradient(123deg, #e5f4ff 0%, #efe7ff 100%)',
                  borderRadius: 12,
                  border: 'none',
                },
                subItem: { background: '#ffffffa6' },
              }}
              onItemClick={(info) => {
                onSubmit(info.data.description as string);
              }}
              className={styles.chatPrompt}
            />
          </Flex>*/}
                </Space>
            )}
        </div>
    );
    const senderHeader = (
        <Sender.Header
            title="Upload File"
            open={attachmentsOpen}
            onOpenChange={setAttachmentsOpen}
            styles={{content: {padding: 0}}}
        >
            <Attachments
                beforeUpload={() => false}
                items={attachedFiles}
                onChange={(info) => setAttachedFiles(info.fileList)}
                placeholder={(type) =>
                    type === 'drop'
                        ? {title: 'Drop file here'}
                        : {
                            icon: <CloudUploadOutlined/>,
                            title: 'Upload files',
                            description: 'Click or drag files to this area to upload',
                        }
                }
            />
        </Sender.Header>
    );
    const chatSender = (
        <>
            {/* 🌟 提示词 */}
            <Prompts
                items={SENDER_PROMPTS}
                onItemClick={(info) => {
                    onSubmit(info.data.description as string);
                }}
                styles={{
                    item: {padding: '6px 12px'},
                }}
                className={styles.senderPrompt}
            />
            {/* 🌟 输入框 */}
            <Sender
                value={inputValue}
                header={senderHeader}
                onSubmit={() => {
                    onSubmit(inputValue);
                    setInputValue('');
                }}
                onChange={setInputValue}
                onCancel={() => {
                    abortController.current?.abort();
                }}
                prefix={
                    <Button
                        type="text"
                        icon={<PaperClipOutlined style={{fontSize: 18}}/>}
                        onClick={() => setAttachmentsOpen(!attachmentsOpen)}
                    />
                }
                loading={loading}
                className={styles.sender}
                allowSpeech
                actions={(_, info) => {
                    const {SendButton, LoadingButton, SpeechButton} = info.components;
                    return (
                        <Flex gap={4}>
                            <SpeechButton className={styles.speechButton}/>
                            {loading ? <LoadingButton type="default"/> : <SendButton type="primary"/>}
                        </Flex>
                    );
                }}
                placeholder="Ask or input / use skills"
            />
        </>
    );

    useEffect(() => {
        // history mock
        if (messages?.length) {
            setMessageHistory((prev) => ({
                ...prev,
                [curConversation]: messages,
            }));
        }
    }, [messages]);

    // ==================== Render =================
    return (
        <div className={styles.layout}>
            {/* 条件渲染侧边栏 */}
            {!isPreviewMode && chatSider}

            <div className={styles.chat} style={{
                width: isPreviewMode ? '50%' : 'calc(100% - 280px)', // 修改为动态计算宽度
                marginLeft: !isPreviewMode ? '280px' : '0', // 新增：侧边栏显示时的偏移
                transition: 'all 0.3s ease-in-out' // 扩展过渡效果
            }}>
                {chatList}
                {chatSender}
            </div>

            {/* 修改预览区域样式 */}
            <div style={{
                width: '50%',
                height: 'calc(100vh - 16px)',
                backgroundColor: 'white',
                boxShadow: '-2px 0 8px rgba(0, 0, 0, 0.15)',
                transform: isSidebarVisible ? 'translateX(0)' : 'translateX(100%)',
                transition: 'transform 0.3s ease-in-out',
                position: 'fixed',
                right: 0,
                top: 0,
                zIndex: 999,  // 从 1000 调整为 999
                display: 'flex',
                flexDirection: 'column',
                boxSizing: 'border-box'
            }}>
                <div style={{padding: '16px', flexShrink: 0}}>
                    <h3>HTML 预览</h3>
                    <button
                        style={{
                            position: 'fixed',  // 从 absolute 改为 fixed
                            top: '16px',
                            right: '16px',
                            zIndex: 1002,
                            border: 'none',
                            background: 'transparent',
                            fontSize: '16px',
                            cursor: 'pointer'
                        }}
                        onClick={() => {
                            setIsSidebarVisible(false);
                            setIsPreviewMode(false); // 新增：退出预览模式
                        }}
                    >
                        ×
                    </button>
                </div>
                <div style={{
                    padding: '16px',
                    borderTop: '1px solid #e8e8e8',
                    flexGrow: 1,
                    height: 'calc(100% - 60px)', // 增加高度计算
                    boxSizing: 'border-box'
                }}>
                    <iframe
                        srcDoc={sidebarContent}
                        title="HTML Preview"
                        style={{
                            width: '100%',
                            height: '100%',
                            border: 'none',
                            backgroundColor: '#fff' // 增加背景色
                        }}
                    />
                </div>
            </div>

        </div>
    );
};

export default Independent;
